//
//  ZLLDiskCache.m
//  Test
//
//  Created by Vincent on 2017/2/13.
//  Copyright © 2017年 Vincent. All rights reserved.
//

#import "ZLLDiskCache.h"




@implementation ZLLDiskCache


//缓存对象
+(void)cacheObject:(id<NSCoding>)rootObject forKey:(NSString *)key atPath:(NSString *)path completionBlock:(ZLLDiskCacheBlock)block{
    
    NSURL *url = [self encodeFileURLWithPath:path forKey:key];
    NSError *err = [self createDirectoryWithURL:[NSURL fileURLWithPath:[url.path stringByDeletingLastPathComponent]]];
    if([NSKeyedArchiver archiveRootObject:rootObject toFile:url.path]){
        err = nil;
    }
    else{
        if(err==nil){//缓存失败（归档对象失败）
            err = [NSError errorWithDomain:@"archive object failure" code:0 userInfo:nil];
        }
    }
    
    if(block){
        block(key,rootObject,url,err);
    }
}

/**构造缓存的路径
 *@param    path        缓存的路径
 *@param    key         缓存的键值
 *@return   返回构建的文件路径
 */

+(NSURL *)encodeFileURLWithPath:(NSString *)path forKey:(NSString *)key{
    NSString *tmStr = [NSString stringWithFormat:@"%@/%@",path,key];
    if(tmStr.length==0){
        return nil;
    }
    CFStringRef escapeStr = CFSTR(".:/");
    CFStringRef urlStr = CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)tmStr, escapeStr);
    
    return [NSURL fileURLWithPath:(__bridge_transfer NSString *)urlStr];
}

/**创建文件目录
 *@param    url        文件路径
 *
 */
+(NSError *)createDirectoryWithURL:(NSURL *)url{
    
    if([[NSFileManager defaultManager] fileExistsAtPath:url.path]==NO){
        
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:&error];
        return error;
    }
    return nil;
}

//获取缓存的对象
+(void)objectForKey:(NSString *)key atPath:(NSString *)path completionBlock:(ZLLDiskCacheBlock)block{
    
    NSURL *url = [self encodeFileURLWithPath:path forKey:key];
    id obj = [NSKeyedUnarchiver unarchiveObjectWithFile:url.path];
    if(block){
        block(key,obj,url,nil);
    }
}

//删除缓存对象
+(void)removeObjectForKey:(NSString *)key atPath:(NSString *)path completionBlock:(ZLLDiskCacheBlock)block{
    
    NSURL *url = [self encodeFileURLWithPath:path forKey:key];
    id obj = [NSKeyedUnarchiver unarchiveObjectWithFile:url.path];
    
    NSFileManager *fMag = [NSFileManager defaultManager];
    NSError *err = nil;
    [fMag removeItemAtURL:url error:&err];
    
    if(block){
        block(key,obj,url,err);
    }
}


@end
